package com.github.permissiondog.cancanpandroid.repository.impl;

import android.util.Log;
import android.widget.Toast;

import com.github.permissiondog.cancanpandroid.MyApplication;
import com.github.permissiondog.cancanpandroid.model.Application;
import com.github.permissiondog.cancanpandroid.model.TableAnswer;
import com.github.permissiondog.cancanpandroid.repository.ApplicationRepository;
import com.github.permissiondog.cancanpandroid.repository.api.ApplicationApiService;
import com.github.permissiondog.cancanpandroid.repository.api.request.ApproveApplicationRequest;
import com.github.permissiondog.cancanpandroid.repository.api.request.ConfirmApplicationRequest;
import com.github.permissiondog.cancanpandroid.repository.api.request.CreateApplicationRequest;
import com.github.permissiondog.cancanpandroid.repository.api.response.ApplicationInfoResponse;
import com.github.permissiondog.cancanpandroid.repository.api.response.ApplicationResponse;
import com.github.permissiondog.cancanpandroid.repository.api.response.ApplicationsResponse;
import com.github.permissiondog.cancanpandroid.repository.api.response.BaseResponse;
import com.github.permissiondog.cancanpandroid.util.CallBack;
import com.github.permissiondog.cancanpandroid.util.NetUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ApplicationRepositoryImpl implements ApplicationRepository {
    private static ApplicationRepository INSTANCE;
    public static synchronized ApplicationRepository getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new ApplicationRepositoryImpl();
        }
        return INSTANCE;
    }
    private final ApplicationApiService applicationApiService;
    private ApplicationRepositoryImpl() {
        this.applicationApiService = NetUtil.RETROFIT.create(ApplicationApiService.class);
    }
    @Override
    public void getApplicantApplications(CallBack<List<Application>> applications) {
        applicationApiService.getApplicantApplications().enqueue(new Callback<>() {
            @Override
            public void onResponse(Call<ApplicationsResponse> call, Response<ApplicationsResponse> response) {
                if (!response.isSuccessful() || response.body() == null) {
                    Toast.makeText(MyApplication.getInstance().getApplicationContext(), "网络错误", Toast.LENGTH_LONG).show();
                    return;
                }
                if (!response.body().isOk()) {
                    Toast.makeText(MyApplication.getInstance().getApplicationContext(), "获取申请列表失败", Toast.LENGTH_LONG).show();
                    return;
                }
                applications.callback(response.body().getApplications().stream().filter(app -> !app.isConfirmed()).collect(Collectors.toList()));
            }

            @Override
            public void onFailure(Call<ApplicationsResponse> call, Throwable t) {
                Log.w("request", "获取申请列表失败", t);
            }
        });
    }
    @Override
    public void getApproverApplications(CallBack<List<Application>> applications) {
        applicationApiService.getApproverApplications().enqueue(new Callback<>() {
            @Override
            public void onResponse(Call<ApplicationsResponse> call, Response<ApplicationsResponse> response) {
                if (!response.isSuccessful() || response.body() == null) {
                    Toast.makeText(MyApplication.getInstance().getApplicationContext(), "网络错误", Toast.LENGTH_LONG).show();
                    return;
                }
                if (!response.body().isOk()) {
                    Toast.makeText(MyApplication.getInstance().getApplicationContext(), "获取申请列表失败", Toast.LENGTH_LONG).show();
                    return;
                }
                applications.callback(response.body().getApplications());
            }

            @Override
            public void onFailure(Call<ApplicationsResponse> call, Throwable t) {
                Log.w("request", "获取申请列表失败", t);
            }
        });
    }

    @Override
    public void getApplicationInfo(int applicationId, CallBack<ApplicationInfoResponse> applicationInfo) {
        applicationApiService.getApplicationInfo(applicationId).enqueue(new Callback<>() {
            @Override
            public void onResponse(Call<ApplicationInfoResponse> call, Response<ApplicationInfoResponse> response) {
                if (!response.isSuccessful() || response.body() == null) {
                    Toast.makeText(MyApplication.getInstance().getApplicationContext(), "网络错误", Toast.LENGTH_LONG).show();
                    return;
                }
                if (!response.body().isOk()) {
                    Toast.makeText(MyApplication.getInstance().getApplicationContext(), "获取申请信息失败", Toast.LENGTH_LONG).show();
                    return;
                }
                applicationInfo.callback(response.body());
            }

            @Override
            public void onFailure(Call<ApplicationInfoResponse> call, Throwable t) {
                Log.w("request", "获取申请信息失败", t);
            }
        });
    }

    @Override
    public void createApplication(int templateId, String reason, String imageSha, CallBack<Application> application) {
        TemplateRepositoryImpl.getInstance().getTemplateQuestions(templateId, questions -> {
            var request = new CreateApplicationRequest();
            request.setTemplateId(templateId);
            var answers = new ArrayList<TableAnswer>();
            var reasonAnswer = new TableAnswer();
            reasonAnswer.setQuestionId(questions.stream().filter(q -> q.getTitle().equals("申请原因")).findAny().get().getId());
            reasonAnswer.setAnswer(reason);
            var imageAnswer = new TableAnswer();
            imageAnswer.setQuestionId(questions.stream().filter(q -> q.getTitle().equals("上传证明")).findAny().get().getId());
            imageAnswer.setAnswer(imageSha);

            answers.add(reasonAnswer);
            answers.add(imageAnswer);
            request.setAnswers(answers);
            applicationApiService.createApplication(request).enqueue(new Callback<>() {
                @Override
                public void onResponse(Call<ApplicationResponse> call, Response<ApplicationResponse> response) {
                    if (!response.isSuccessful() || response.body() == null) {
                        Toast.makeText(MyApplication.getInstance().getApplicationContext(), "网络错误", Toast.LENGTH_LONG).show();
                        return;
                    }
                    if (!response.body().isOk()) {
                        Toast.makeText(MyApplication.getInstance().getApplicationContext(), "创建申请失败", Toast.LENGTH_LONG).show();
                        return;
                    }
                    application.callback(response.body().getApplication());
                }

                @Override
                public void onFailure(Call<ApplicationResponse> call, Throwable t) {
                    Log.w("request", "创建申请失败", t);
                }
            });
        });
    }

    @Override
    public void approveApplication(int applicationId, boolean approve, String opinion, CallBack<Boolean> ok) {
        var request = new ApproveApplicationRequest();
        request.setApplicationId(applicationId);
        request.setApprove(approve);
        request.setOpinion(opinion);
        applicationApiService.approveApplication(request).enqueue(new Callback<>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                if (!response.isSuccessful() || response.body() == null) {
                    Toast.makeText(MyApplication.getInstance().getApplicationContext(), "网络错误", Toast.LENGTH_LONG).show();
                    return;
                }
                if (!response.body().isOk()) {
                    Toast.makeText(MyApplication.getInstance().getApplicationContext(), "审批失败", Toast.LENGTH_LONG).show();
                    return;
                }
                ok.callback(response.body().isOk());
            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {
                Log.w("request", "审批失败", t);
            }
        });

    }

    @Override
    public void confirmApplication(int applicationId, CallBack<Boolean> ok) {
        var request = new ConfirmApplicationRequest();
        request.setApplicationId(applicationId);
        applicationApiService.confirmApplication(request).enqueue(new Callback<>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                if (!response.isSuccessful() || response.body() == null) {
                    Toast.makeText(MyApplication.getInstance().getApplicationContext(), "网络错误", Toast.LENGTH_LONG).show();
                    return;
                }
                if (!response.body().isOk()) {
                    Toast.makeText(MyApplication.getInstance().getApplicationContext(), "确认审批失败", Toast.LENGTH_LONG).show();
                    return;
                }
                ok.callback(response.body().isOk());
            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {
                Log.w("request", "确认审批失败", t);
            }
        });
    }
}
